package com.cdel.akka.coordinate;

import scala.concurrent.stm.Ref;
import scala.concurrent.stm.japi.STM;
import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.transactor.Coordinated;

public class EmployeeActor extends UntypedActor {

	private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);

    private Ref.View<Integer> count = STM.newRef(10);//员工账户

    @Override
    public void onReceive(Object o) throws Throwable {
    	//如果是Coordinated，则当前actor会自动加入Coordinated指定的事务。
        if(o instanceof Coordinated){
            Coordinated coordinated = (Coordinated) o;
            int downCount = (int) coordinated.getMessage();//员工增加的工资

            //定义原子操作，在这个操作中将修改雇员账户余额。
            try {
                coordinated.atomic(() -> STM.increment(count, downCount));//Employee增加工资
            }catch (Exception e){
            	//注意这里异常要及时处理，否则异常会一直扩散，导致回退到系统刚启动时的初始状态！
            	e.printStackTrace();
            }

        }else if("getCount".equals(o)){
            getSender().tell(count.get(), getSelf());
        }else{
            unhandled(o);
        }
    }

}
